package com.ruoyi.web.controller.system;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.secure.BCrypt;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.system.domain.App;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.SysRegisterService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 注册验证
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
public class SysRegisterController extends BaseController {

    private final SysRegisterService registerService;
    private final ISysUserService userService;
    private final ISysConfigService configService;

    /**
     * 用户注册
     */
    @SaIgnore
    @PostMapping("/register")
    public R<Void> register(@Validated @RequestBody RegisterBody user) {
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return R.fail("当前系统没有开启注册功能！");
        }
        registerService.register(user);
        return R.ok();
    }
    /**
     * 手机用户注册
     */
    @SaIgnore
    @PostMapping("/appRegister")
    public R<Void> appRegister(@Validated @RequestBody SysUser user) throws Exception {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            throw new Exception("此人已注册过请勿重复注册");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNickUnique(user))) {
            throw new Exception(user.getNickName()+"昵称已经存在");
        }
//        registerService.register(user);
        user.setPassword(BCrypt.hashpw(user.getPassword()));
        boolean flag = userService.registerUser(user);
        SysUser sysUser=userService.selectObject(user.getUserName(),user.getNickName(),user.getPassword());
        App app=new App();
        app.setUserId(sysUser.getUserId());
        app.setCategory(String.valueOf(0));
        userService.addApp(app);
        return R.ok();
    }
}
